<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/31
 * Time: 14:19
 */

namespace Home\Logic;


use Common\Utils\ExpressBirdUtils;
use Home\Model\Page;
use Think\Exception;
use Think\Log;

class OrderLogic
{
    /**根据类型获取订单列表
     * @param $type 类型 0所有订单 1待付款 2待发货 3待收货 4待评价
     * @param $isRead=false 是否标记为已读
     * @return mixed
     */
    public function getOrderList($type,$isRead=false){
        $user = session('user');
        $user = D('Users')->where(array('user_id'=>$user['user_id']))->find();
        $map['user_id'] = $user['user_id'];
        $map['is_delete'] = 0;
        switch ($type){
            case 0: //所有订单
                break;
            case 1://待付款
                $map['pay_status'] = 0;
//                $map['ORDER_STATUS'] = 1;//已确认
                break;
            case 2://待发货
                $map['shipping_status'] = array('neq'=>1);
                $map['order_status'] = 1;
                break;
            case 3://待收货
                $map['shipping_status'] = 1;
                $map['order_status'] = 1;
                break;
            case 4://待评价
                $map['order_status'] = 2;
                break;
        }
        $model = D('Order');
        $orderList = $model->where($map)->order('order_id desc')->select();
        $model->startTrans();
        try {
            foreach ($orderList as $key => $value) {
//                if($isRead) {
//                    $orderList[$key]['is_read'] = 1;
//                    $model->save($orderList[$key]);
//                }
                $order_id = $orderList[$key]['order_id'];
                $goodsList = D('OrderGoods')->where(array('order_id' => $order_id, 'is_comment'=>0))->select();
                $orderList[$key]['goodsList'] = $goodsList;
                $orderList[$key]['goods_count'] = count($goodsList);
            }
            $model->commit();
        }catch (Exception $e){
            $model->rollback();
        }

        return $orderList;
    }

    //生成退款请求
    function  applyRefund($orderId, $userId){
        $order = M('order')->where(array('order_id'=> $orderId, 'user_id'=> $userId))->find();
        //判断订单是否存在
        if(!$order)
            return array('status'=> -1, 'msg'=> '订单不存在');
        //判断订单状态
        if(!($order['shipping_status'] != 1 && $order['order_status']==1))
            return array('status'=> -1, 'msg' => '订单状态有误');

        //订单状态设置为作废
        $order['order_status'] = 5;
        M('order')->save($order);

        //获取订单支付方式
        if($order['pay_name'] == '余额支付')
            $pay_type = 1;
        else if($order['pay_name'] == '微信支付')
            $pay_type = 2;
        //向退款单插入数据
        $refundData = array(
                'order_sn'     =>  $order['order_sn'],
                'user_id'      =>  $order['user_id'],
                'refund_money' =>  $order['order_amount'],
                'create_time'  =>  time(),
                'status'       =>  0,
                'pay_type'     =>  $pay_type
        );
        $fundId = M('refund')->add($refundData);
        if($fundId){
            return array('status'=> 1, 'msg'=> '申请成功请等待审核');
        }
        else
            return array('status'=> -1, 'msg'=> '申请失败');
    }


    public function getOrderListByType($allOrderList,$type){
        $resultList = array();
        foreach ($allOrderList as $key => $value){
            switch ($type){
                case 0: //所有订单
                    $resultList = $allOrderList;
                    break;
                case 1://待付款
                    if($allOrderList[$key]['pay_status'] == 0){
                        $resultList[] = $allOrderList[$key];
                    }
                    break;
                case 2://待发货
                    if($allOrderList[$key]['shipping_status'] != 1 && $allOrderList[$key]['order_status']==1){
                        $resultList[] = $allOrderList[$key];
                    }
                    break;
                case 3://待收货
                    if($allOrderList[$key]['shipping_status'] == 1 && $allOrderList[$key]['order_status']==1){
                        $resultList[] = $allOrderList[$key];
                    }
                    break;
                case 4://待评价
                    if($allOrderList[$key]['order_status'] == 2){
                        $resultList[] = $allOrderList[$key];
                    }
                    break;
            }
        }
        return $resultList;
    }

    public function getUnReadOrderNum(){
        $allOrderList = $this->getOrderList(0);
        $all = 0;
        $pay = 0;
        $shipment = 0;//待发货
        $received = 0;//待收货
        $evaluation =0;//待评价.
        $return = 0;//退换货
        foreach ($allOrderList as $key=>$value){
            $all++;
            if($allOrderList[$key]['pay_status'] == 0 ){
                $pay++;
            }
            if($allOrderList[$key]['shipping_status'] != 1 && $allOrderList[$key]['order_status']==1 ){
                $shipment++;//待发货
            }
            if($allOrderList[$key]['shipping_status'] == 1 && $allOrderList[$key]['order_status']==1){
                $received++;
            }
            if($allOrderList[$key]['order_status'] == 2 ){
                $evaluation++;
            }
        }
        $user = session('user');
        $return = D('ReturnGoods')->where(array('user_id'=>$user['user_id'],'status'=>array('neq',2)))->count();
        return array('all'=>$all,'pay'=>$pay,'shipment'=>$shipment,'received'=>$received,'evaluation'=>$evaluation,'return'=>$return);
    }

    /**
     * 根据id获取订单
     * @param $order_id 订单id
     * @return mixed 订单详情
     */
    public function getOrderById($order_id){
        $map['is_delete'] = 0;
        $map['order_id'] = $order_id;
        $model = D('Order');
        $order = $model->where($map)->find();
        if($order) {
            $goodsList = D('OrderGoods')->where(array('order_id' => $order_id))->order('rec_id desc')->select();
            $order['goodsList'] = $goodsList;
            $order['goods_count'] = count($goodsList);
        }
        return $order;
    }

    public function getNoCommentOrderGoodsById($order_id){
        $map['is_delete'] = 0;
        $map['order_id'] = $order_id;
        $model = D('Order');
        $order = $model->where($map)->find();
        if($order) {
            $goodsList = D('OrderGoods')->where(array('order_id' => $order_id,'is_comment'=>0))->order('rec_id desc')->select();
            return $goodsList;
        }else{
            return null;
        }
    }

    /**
     * 通过订单id获取物流信息
     * @param $order_id 订单id
     * @return mixed 物流信息 state:2-在途中,3-签收,4-问题件
     */
    public function getLogisticsInfo($order_id){
        $utils = new ExpressBirdUtils();
        $map['order_id'] = $order_id;
        $model = M('delivery_doc');
        $order = $model->where($map)->find();
        if($order) {
            $result = $utils->getOrderTracesByJson($order['invoice_no'],$order['shipping_code']);
            $data = json_decode($result,true);
            $data['Traces'] = array_reverse($data['Traces']);
            $data['delivery'] = $order;
            return $data;//转为数组
        }
        return false;
    }

    /**
     * 获取退换货商品列表
     * @param $type 0退款 1退货
     * @param $user_id 用户id
     * @return mixed
     */
    public function getReturnGoodsList($type,$user_id){
        $user = D('Users')->where(array('user_id'=>$user_id))->find();
        $map['tp_return_goods.user_id'] = $user['user_id'];
        $map['tp_return_goods.type'] = $type;
        $list = D('ReturnGoods')
            ->join('LEFT JOIN tp_goods g ON g.goods_id=tp_return_goods.goods_id')
//            ->join('LEFT JOIN tp_spec_goods_price s ON s.key=tp_return_goods.spec_key')
            ->where($map)->field('tp_return_goods.*,g.original_img,g.goods_name')->select();
        foreach ($list as $key=>$value){
//            $keyValues = explode(',',$value['key_name']);
//            if(isset($keyValues)){
//                $list[$key]['keyValues'] = $keyValues;
//            }else{
//                $list[$key]['keyValues'] = null;
//            }

            $list[$key]['addtime'] = date('Y-m-d',$list[$key]['addtime']);
        }
        return $list;
    }

    /**
     * 添加退货商品
     * @param $rec_id 订单商品id
     * @param $content 退货原因
     * @return int 0添加失败 1成功 2已经添加到退货单中 3该商品不存在
     */
    public function addReturnGoods($rec_id,$content){
        $model = M();
        $model->startTrans();
        $map['rec_id'] = ':rec_id';
        $bind[':rec_id'] = $rec_id;
        $orderGoods = $model->table('tp_order_goods')->where($map)->bind($bind)->find();
        if(!$orderGoods){
            return 3;
        }
        $order_id = $orderGoods['order_id'];
        $goods_id = $orderGoods['goods_id'];
        $spec_key = $orderGoods['spec_key'];
        $goods = D('ReturnGoods')
            ->where(array('order_id' => $order_id,'goods_id' => $goods_id,'spec_key' => $spec_key))
            ->find();
        if($goods){
            return 2;
        }
        try {
            $order = D('Order')->where(array('order_id'=>$order_id))->find();

//            $orderGoods = D('OrderGoods')->where(array('order_id' => $order_id, 'goods_id' => $goods_id))->find();
            Log::write('OrderGoods sql:'.D('OrderGoods')->getLastSql(),'WARN');
            $goods['order_id'] = $order_id;
            $goods['order_sn'] = $order['order_sn'];
            $goods['goods_id'] = $goods_id;
            $goods['type'] = 1;
            $goods['spec_key'] = $orderGoods['spec_key'];
            $goods['addtime'] = time();
            $goods['status'] = 0;
            $user = session('user');
            $goods['user_id'] = $user['user_id'];
            $goods['return_no'] = build_order_no();
            $money = $orderGoods['goods_num'] * $orderGoods['goods_price'];
            $goods['refund_price'] = $money;
            $goods['trade_price'] = $money;
            $goods['reason'] = $content;
            $model->table('tp_return_goods')->add($goods);
            $model->table('tp_order_goods')
                ->where(array('order_id' => $order_id, 'goods_id' => $goods_id))
                ->setField('is_send',5);//退货中
            $count = $model->table('tp_order_goods')->where(array('order_id' => $order_id, 'is_send' => array('neq',5)))->count();
            if($count == 0){
                //都退货
                $model->table('tp_order')->where(array('order_id' => $order_id))->setField('is_delete', 1);//删除该订单
            }
//            $model->table(array('order_id'=>$order_id))-
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            return 0;
        }
    }

    /**
     * 添加
     * @param $order_id 订单id
     * @param $goods_id 商品id
     * @param $money 金额
     * @param $remark 备注
     */
    public function addExchangeGoods($order_id,$goods_id,$money,$remark){

    }

    /**
     * 删除订单
     * @param $order_id 订单id
     * @return int 1成功 2已经删除 3错误
     */
    public function deleteOrder($order_id){
        $map['order_id'] = ':order_id';
        $bind[':order_id'] = $order_id;
        $is_delete = D('Order')->where($map)->bind($bind)->getField('is_delete');
        if($is_delete == '1'){
            return 2;
        }
        try{
            D('Order')->where($map)->bind($bind)->setField('is_delete',1);//标记删除
            return 1;
        }catch (Exception $e){
            return 3;
        }
    }

    /**
     * 确认收货
     * @param $order_id 订单id
     * @return int 1成功 2不能确认 3确认失败
     */
    public function confirmReceipt($order_id){
        $map['order_id'] = ':order_id';
        $bind[':order_id'] = $order_id;
        $order = D('Order')->where($map)->bind($bind)->find();
        $model = M();
        $model->startTrans();
        try{
            if($order['order_status'] == '1' && $order['shipping_status'] =='1'){
                $orderGoodsList = $model->table('tp_order_goods')
                    ->where(array('order_id' => $order['order_id']))->select();
                foreach ($orderGoodsList as $key => $value) {
                    if($orderGoodsList[$key]['is_send'] == 5){//该商品已经退货
                        $orderGoodsList[$key]['is_comment'] = 1;
                    }
                    $orderGoodsList[$key]['is_send'] = 6;//确认收货
                    $model->table('tp_order_goods')->where(array('rec_id'=>$orderGoodsList[$key]['rec_id']))->save($orderGoodsList[$key]);
                }
                $model->table('tp_order')->where($map)->bind($bind)->setField('order_status',2);//修改订单状态 已经确认
                $model->commit();
                return 1;
            }else{
                return 2;
            }
        }catch (Exception $e){
            $model->rollback();
            return 3;
        }
    }

    /**
     * 发表评论
     * @param $commentList 表单列表
     * @param $order_id 订单id
     * @param $model　事务model
     * @param $user 用户
     * @return int status 0评论不能为空 1成功 2失败
     */
    public function replyComments($commentList,$order_id, $model, $user)
    {
        try {
            foreach ($commentList as $key => $value) {
                if (empty($commentList[$key]['content'])) {
                    $model->rollback();
                    return 0;//评论不能为空

                }
                $map['rec_id'] = ':rec_id';
                $bind[':rec_id'] = $commentList[$key]['rec_id'];
                $orderGoods = $model->table('tp_order_goods')->where($map)->bind($bind)->find();
                $comment['goods_id'] = $commentList[$key]['goods_id'];
                $comment['order_id'] = $orderGoods['order_id'];
                $comment['content'] = $commentList[$key]['content'];
                $type = $commentList[$key]['type'];
                if ($type == '' || ($type != '1' || $type != '2' || $type != '0')) {
                    $type = 0;
                }
                $comment['type'] = $type;
                $comment['add_time'] = time();
                $comment['is_show'] = 1;
                $comment['user_id'] = $user['user_id'];
                $comment['username'] = $user['nickname'];
                $comment['ip_address'] = get_ip();
                $comment['spec_name'] = $orderGoods['spec_key_name'];
                $comment_id = $model->table('tp_comment')->add($comment);
                $orderGoods['is_comment'] = 1;//置为已经评论状态
                $orderGoods['is_send'] = 5;//置为已经完成状态
                $model->table('tp_order_goods')->save($orderGoods);
                $this->addCommentImages($comment_id,$commentList[$key]['image_urls'],$model);
            }
            //修改订单状态为已经完成状态
            $id = $model->table('tp_order')->where(array('order_id' => $order_id))->setField('order_status', 4);
            return 1;
        } catch (Exception $e) {
            $model->rollback();
            return 2;
        }
    }

    /**
     * 发表单条评论
     * @param $comment 评论
     * @param $order_id 订单id
     * @param $user 用户id
     * @param $rec_id
     * @return int status 0评论不能为空 1全部完成 2失败 3部分完成
     */
    public function replyComment($comment,$order_id,$user,$rec_id){
        $model = M();
        $model->startTrans();
        try {
            if (empty($comment['content'])) {
                $model->rollback();
                return 0;//评论不能为空
            }
            $map['rec_id'] = ':rec_id';
            $bind[':rec_id'] = $rec_id;
            $orderGoods = $model->table('tp_order_goods')->where($map)->bind($bind)->find();
            $comment['order_id'] = $orderGoods['order_id'];
            $type = $comment['type'];
            if ($type == '' || ($type != '1' || $type != '2' || $type != '0')) {
                $type = 0;
            }
            $comment['type'] = $type;
            $comment['add_time'] = time();
            $comment['is_show'] = 1;
            $comment['user_id'] = $user['user_id'];
            $comment['username'] = $user['nickname'];
            $comment['ip_address'] = get_ip();
            $comment['spec_name'] = $orderGoods['spec_key_name'];
            $comment_id = $model->table('tp_comment')->add($comment);
            $this->addCommentImages($comment_id, $comment['image_urls'], $model);
            $orderGoods['is_comment'] = 1;//置为已经评论状态
            $orderGoods['is_send'] = 5;//置为已经完成状态
//            $model->table('tp_order_goods')->save($orderGoods);
            $model->table('tp_order_goods')->where($map)->bind($bind)->setField('is_comment',1);
            $model->table('tp_order_goods')->where($map)->bind($bind)->setField('is_send',5);
            $count = $model->table('tp_order_goods')->where(array('order_id' => $order_id, 'is_comment' => 0))->count();
            if ($count == 0) {
                //修改订单状态为已经完成
                $id = $model->table('tp_order')->where(array('order_id' => $order_id))->setField('order_status', 4);
                $model->commit();
                return 1;
            } else {
                $model->commit();
                return 3;
            }
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 2;
        }
    }

    /**
     * 订单所有商品是否评论
     * @param $order_id 订单id
     * @return bool
     */
    public function isCompleteComment($order_id){
        $count = D('OrderGoods')->where(array('order_id' => $order_id, 'is_comment' => 0))->count();
        if($count == 0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 判断某个商品是否已经评论
     * @param $rec_id
     * @return bool
     */
    public function isCompleteCommentByOrderGoods($rec_id){
        $is_comment = D('OrderGoods')->where(array('rec_id'=>$rec_id))->getField('is_comment');
        return $is_comment == 1;
    }

    /**
     * 添加图片评论
     * @param $comment_id 评论id
     * @param $image_urls 图片url
     * @param $model
     */
    public function addCommentImages($comment_id,$image_urls,$model){
        $image['comment_id'] = $comment_id;
        foreach ($image_urls as $key => $value) {
            $image['image_url'] = $value;
            $model->table('tp_comment_image')->add($image);
        }
    }

    /**获取用户免费订单列表
     * @param $user_id 用户id
     * @param $pagenum 页数
     * @param $pagesize 页面大小
     * @return mixed 免费订单列表
     */
    public function freeOrderList($user_id,$pagenum,$pagesize){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['tp_spec_goods.user_id'] = ':user_id';
        $bind[':user_id'] = $user_id;
        $moneyLogList = D('SpecGoods')
            ->where($map)->bind($bind)->limit($limit)
            ->select();
        $data['list'] = $moneyLogList;
        $count = D('SpecGoods')->where($map)->bind($bind)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        //分页数据
//        $page['cpage'] = $pagenum;//当前页面
//        $page['totalnum'] = floor(($count + $pagesize - 1) / $pagesize);
        $data['page'] = $page;

        return $data;
    }

    /**获取配送员订单列表
     * @param $user_id 用户id
     * @param $pagenum 页数
     * @param $pagesize 页面大小
     * @return mixed 免费订单列表
     */
    public function dispatchOrder($user_id,$pagenum,$pagesize){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['tp_tak_spec_goods.send_user_id'] = ':user_id';
        $bind[':user_id'] = $user_id;
        $moneyLogList = D('TakSpecGoods')
            ->where($map)->bind($bind)->limit($limit)
            ->select();
        $data['list'] = $moneyLogList;
        $count = D('TakSpecGoods')->where($map)->bind($bind)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        //分页数据
//        $page['cpage'] = $pagenum;//当前页面
//        $page['totalnum'] = floor(($count + $pagesize - 1) / $pagesize);
        $data['page'] = $page;

        return $data;
    }

    public function confirmCancelTakeSpecGoods($user_id, $tak_spec_goods_id, $type){
        $tak_spec = M('TakSpecGoods')->where(array('id'=>$tak_spec_goods_id))->find();
        $user = M('users')->where(array('user_id'=>$user_id))->find();
        $logic = new UserLogic();
        if($user['type'] == 0)
            return  array('status'=>-1, 'msg'=>'没有权限进行操作');
        if($tak_spec){
            if($tak_spec['status'] == 0)
                $res = array('status'=>-1, 'msg'=>'该订单未设置配送员');
            else
            {
                if($tak_spec['status'] == 2)
                    $res = array('status'=>-1, 'msg'=>'该订单已送达');
                else
                {

                    $tak_spec['status'] = $type;
                    M('tak_spec_goods')->save($tak_spec);
                    if($type==2){
                        $rebateMoney = M('config')->where(array('id'=>74))->getField('value');
                        $logic->rebateLastUser((double)$rebateMoney, $tak_spec['user_id']);
                    }
                    $res = array('status'=>1, 'msg'=>'操作成功');
                }
            }
        }
        else
            $res = array('status'=>-1, 'msg'=>'未找到该条订单');

        return $res;
    }





    public function addOrder($user_id,$address_id,$shipping_code,$invoice_title,$coupon_id = 0,$car_price, $order_goods, $order_sn, $type, $user_note=''){
        /* $order_count = M('Order')->where("user_id= $user_id and order_sn like '".date('Ymd')."%'")->count(); // 查找购物车商品总数量
         if($order_count >= 50)
             return array('code'=>-1,'message'=>'一天只能下50个订单','result'=>array(), 'count'=>1);*/

        if($address_id) {
            $address = M('UserAddress')->where("address_id = $address_id")->find();
        }
        else{
            $address['address_id'] = 0;
            $address['consignee'] = '';
            $address['province'] = 0;
            $address['city'] = 0;
            $address['district'] = 0;
            $address['twon'] = 0;
            $address['area'] = '';
            $address['address'] = '';
            $address['mobile'] = '';
            $address['zipcode'] = '';
            $address['email'] = '';
        }
        //        $shipping = M('Plugin')->where("code = '$shipping_code'")->find();
        $shipping['name'] = '中通';

        $data = array(
            'order_sn'         => $order_sn, // 订单编号
            'user_id'          =>$user_id, // 用户id
            'consignee'        =>$address['consignee'], // 收货人
            'province'         =>$address['province'],//'省份id',
            'city'             =>$address['city'],//'城市id',
            'district'         =>$address['district'],//'县',
            'twon'             =>$address['twon'],// '街道',
            'address'          =>$address['area'].$address['address'],//'详细地址',
            'mobile'           =>$address['mobile'],//'手机',
            'zipcode'          =>$address['zipcode'],//'邮编',
            'email'            =>$address['email'],//'邮箱',
            'shipping_code'    =>$shipping_code,//'物流编号',
            'shipping_name'    =>$shipping['name'], //'物流名称',
            'invoice_title'    =>$invoice_title, //'发票抬头',
            'goods_price'      =>$car_price['goodsFee'],//'商品价格',
            'shipping_price'   =>$car_price['postFee'],//'物流价格',
            'user_money'       =>$car_price['balance'],//'使用余额',
            'coupon_price'     =>$car_price['couponFee'],//'使用优惠券',
            'integral'         =>($car_price['pointsFee'] * tpCache('shopping.point_rate')), //'使用积分',
            'integral_money'   =>$car_price['pointsFee'],//'使用积分抵多少钱',
            'total_amount'     =>($car_price['goodsFee'] + $car_price['postFee']),// 订单总额
            'order_amount'     =>$car_price['payables'],//'应付款金额',
            'add_time'         =>time(), // 下单时间
            'order_prom_id'    =>$car_price['order_prom_id'],//'订单优惠活动id',
            'order_prom_amount'=>$car_price['order_prom_amount'],//'订单优惠活动优惠了多少钱',
            'type'             =>$type,   //标识是普通商品还是特殊商品
            'is_delete'        =>0,
            'is_read'          =>0,
            'user_note'        =>$user_note, //用户备注
            'address_id'       =>$address['address_id']
        );
        $order_id = M("Order")->data($data)->add();

        if(!$order_id)
            return array('status'=>-1,'msg'=>'添加订单失败','result'=>array(), 'count'=>1);
        // 记录订单操作日志
//        var_dump($shipping);
        logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$user_id);
        $order = M('Order')->where("order_id = $order_id")->find();

        foreach ($order_goods as $key => $val){
//            var_dump($order_goods);
//            return  array('code'=>$order_goods);
            if($val['spec_key']) {
                $key_name = M('spec_goods_price')->where(array('goods_id' => $val['goods_id'], 'key' => $val['spec_key']))->getField('key_name');
             //   $price = M('spec_goods_price')->where(array('goods_id' => $val['goods_id'], 'key' => $val['spec_key']))->getField('price');
            }
            else {
                $val['spec_key'] = '';
                $key_name = '';
               // $price = $val['shop_price'];
            }
            $price = $val['shop_price'];
//            $goods = M('goods')->where("goods_id = {$val['goodsId']} ")->find();
            $data2['order_id']           = $order_id; // 订单id
            $data2['goods_id']           = $val['goods_id']; // 商品id
            $data2['goods_name']         = $val['goods_name']; // 商品名称
            $data2['goods_sn']           = $val['goods_sn']; // 商品货号
            $data2['goods_num']          = $val['goods_num']; // 购买数量
            $data2['market_price']       = $val['market_price']; // 市场价
            $data2['goods_price']        = $price; // 商品价
            $data2['spec_key']           = $val['spec_key']; // 商品规格
            $data2['spec_key_name']      = $key_name; // 商品规格名称
            $data2['sku']           		= $val['sku']; // 商品sku
            $data2['member_goods_price'] = $val['member_goods_price']; // 会员折扣价
            $data2['cost_price']         = $val['cost_price']; // 成本价
            $data2['give_integral']      = $val['give_integral']; // 购买商品赠送积分
            $data2['prom_type']          = $val['prom_type']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
            $data2['prom_id']            = $val['prom_id']; // 活动id
            $data2['image_url']          = $val['original_img'];
            $data2['region_name']        = $val['region_name'];
            $order_goods_id              = M("OrderGoods")->data($data2)->add();
        }

        return array('status'=>0,'msg'=>'提交订单成功','order_id'=>$order_id, 'count'=>1); // 返回新增的订单id

    }


    public function getFreeOrder($user_id){

        $model = M('TakSpecGoods');

        $freeOrderList = $model->where(array('user_id'=>$user_id))->select();

        return $freeOrderList;


    }


}